<template>
  <el-container class="chat-layout">
    <!-- 左侧会话列表 -->
    <el-aside width="320px" class="chat-sidebar">
      <el-header height="60px" class="sidebar-header">
        <div class="header-content">
          <h3>消息</h3>
          <el-button-group>
            <el-button :icon="Search" circle size="small" @click="showSearchDialog = true" />
            <el-button :icon="Plus" circle size="small" />
          </el-button-group>
        </div>
      </el-header>

      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchValue"
          placeholder="搜索会话..."
          :prefix-icon="Search"
          clearable
        />
      </div>

      <!-- 会话列表 -->
      <el-scrollbar class="conversation-scrollbar">
        <div class="conversation-list">
          <div
            v-for="(recent, index) in filteredRecents"
            :key="index"
            :class="{ active: index === selectedIndex }"
            @click="selectedIndex = index"
            class="conversation-item">

            <el-badge :value="getUnreadCount(recent)" :hidden="getUnreadCount(recent) === 0" class="conversation-badge">
              <el-avatar :size="48" :src="'/images/face/' + recent.user.icon" class="conversation-avatar">
                <img :src="'/images/face/' + recent.user.icon" />
              </el-avatar>
            </el-badge>

            <div class="conversation-info">
              <div class="conversation-header">
                <span class="name">{{ recent.user.nickname }}</span>
                <el-tag v-if="recent.user.robot" size="small" type="success" effect="plain">AI</el-tag>
                <span class="time">{{ lastMsgTime(recent.messages) }}</span>
              </div>
              <div class="last-message">
                <el-text class="content" truncated>{{ lastMsgContent(recent.messages) }}</el-text>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-aside>

    <!-- 右侧聊天区域 -->
    <el-container class="chat-main">
      <!-- 空状态 -->
      <el-empty v-if="!currentRecent" description="选择一个会话开始聊天" :image-size="120">
        <template #image>
          <el-icon :size="80" color="#409EFF"><ChatDotRound /></el-icon>
        </template>
      </el-empty>

      <!-- 聊天内容 -->
      <template v-else>
        <!-- 聊天头部 -->
        <el-header height="60px" class="chat-header">
          <div class="chat-info">
            <el-avatar :size="40" :src="'/images/face/' + currentRecent.user.icon" />
            <div class="header-text">
              <h4>{{ currentRecent.user.nickname }}</h4>
              <el-text size="small" type="success">{{ currentRecent.user.robot ? '智能助手' : '在线' }}</el-text>
            </div>
          </div>
          <div class="chat-actions">
            <el-button-group>
              <el-button :icon="VideoCamera" circle />
              <el-button :icon="Phone" circle />
              <el-button :icon="MoreFilled" circle />
            </el-button-group>
          </div>
        </el-header>

        <!-- 聊天内容区域 -->
        <div class="chat-content-wrapper">
          <!-- 消息列表 -->
          <div class="messages-container" ref="wrapper">
            <el-scrollbar class="messages-scrollbar">
              <div class="messages-list">
                <div
                  v-for="(msg, index) in currentRecent.messages"
                  :key="index"
                  class="message-wrapper">

                  <!-- 时间分隔线 -->
                  <div v-if="shouldShowTime(index)" class="time-divider">
                    <el-divider>
                      <el-text size="small" type="info">{{ formatTime(msg.time) }}</el-text>
                    </el-divider>
                  </div>

                  <!-- 消息内容 -->
                  <div class="message-item" :class="{ 'message-self': msg.self }">
                    <el-avatar
                      v-if="!msg.self"
                      :size="36"
                      :src="'/images/face/' + currentRecent.user.icon"
                      class="message-avatar" />

                    <div class="message-content">
                      <!-- 文本消息 -->
                      <el-card v-if="msg.type === 'text' || !msg.type"
                               class="message-bubble text-message"
                               shadow="never">
                        <div v-html="replaceEmoji(msg.content)"></div>
                      </el-card>

                      <!-- 图片消息 -->
                      <div v-else-if="msg.type === 'image'" class="message-bubble image-message">
                        <el-image
                          :src="getImageUrl(msg.fileData.url)"
                          :alt="msg.fileData.name"
                          fit="cover"
                          class="chat-image"
                          :preview-src-list="[getImageUrl(msg.fileData.url)]"
                          preview-teleported
                          loading="lazy"
                        >
                          <template #placeholder>
                            <div class="image-placeholder">
                              <el-icon><Picture /></el-icon>
                              <span>加载中...</span>
                            </div>
                          </template>
                          <template #error>
                            <div class="image-error">
                              <el-icon><Picture /></el-icon>
                              <span>加载失败</span>
                            </div>
                          </template>
                        </el-image>
                        <div v-if="msg.fileData.name" class="image-info">
                          <el-text size="small" type="info">{{ msg.fileData.name }}</el-text>
                        </div>
                      </div>

                      <!-- 视频消息 -->
                      <div v-else-if="msg.type === 'video'" class="message-bubble video-message">
                        <video
                          :src="getImageUrl(msg.fileData.url)"
                          controls
                          preload="metadata"
                          class="chat-video"
                        >
                          您的浏览器不支持视频播放
                        </video>
                        <div v-if="msg.fileData.name" class="video-info">
                          <el-text size="small" type="info">{{ msg.fileData.name }}</el-text>
                        </div>
                      </div>

                      <!-- 音频消息 -->
                      <div v-else-if="msg.type === 'audio'" class="message-bubble audio-message">
                        <div class="audio-player">
                          <div class="audio-icon">🎵</div>
                          <audio
                            :src="getImageUrl(msg.fileData.url)"
                            controls
                            preload="metadata"
                            class="chat-audio"
                          >
                            您的浏览器不支持音频播放
                          </audio>
                        </div>
                        <div v-if="msg.fileData.name" class="audio-info">
                          <el-text size="small" type="info">{{ msg.fileData.name }}</el-text>
                        </div>
                      </div>

                      <!-- 文件消息 -->
                      <el-card v-else-if="msg.type === 'file'"
                               class="message-bubble file-message"
                               shadow="never">
                        <div class="file-content">
                          <el-icon :size="24" color="#409EFF"><Document /></el-icon>
                          <div class="file-details">
                            <el-text class="file-name" truncated>{{ msg.fileData.name }}</el-text>
                            <el-text size="small" type="info">{{ formatFileSize(msg.fileData.size) }}</el-text>
                          </div>
                          <el-button :icon="Download" circle size="small" @click="downloadFile(msg.fileData.url)" />
                        </div>
                      </el-card>

                      <!-- 消息状态 -->
                      <div v-if="msg.self" class="message-status">
                        <el-text size="small" type="info">
                          <el-icon v-if="msg.sending"><Loading /></el-icon>
                          <el-icon v-else color="#67C23A"><Select /></el-icon>
                          {{ msg.sending ? '发送中' : '已发送' }}
                        </el-text>
                      </div>
                    </div>

                    <el-avatar
                      v-if="msg.self"
                      :size="36"
                      :src="'/images/face/' + state.user.icon"
                      class="message-avatar" />
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <!-- 工具栏 -->
            <div class="input-toolbar">
              <div class="input-toolbar-buttons">
                <emoji @update="handleUpdate" v-model="showEmoji">
                  <el-button :icon="ChatLineRound" size="small" />
                </emoji>
                <FileUpload @file-uploaded="handleFileUploaded" @files-uploaded="handleFilesUploaded">
                  <el-button :icon="Paperclip" size="small" />
                </FileUpload>
                <el-button :icon="Picture" size="small" />
                <el-button :icon="Microphone" size="small" />
              </div>
            </div>

            <!-- 输入框 -->
            <div class="input-container">
              <el-input
                v-model="content"
                type="textarea"
                :rows="1"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="输入消息..."
                @keydown.enter.prevent="handleSend"
                @focus="showEmoji = false"
                class="message-input"
              />
              <el-button
                type="primary"
                :icon="Promotion"
                circle
                @click="handleSend"
                :disabled="!content.trim()"
                class="send-button" />
            </div>

            <!-- 警告提示 -->
            <el-alert
              v-if="showWarn"
              title="消息不能为空"
              type="warning"
              :closable="false"
              show-icon
              class="input-warning" />
          </div>
        </div>
      </template>
    </el-container>

    <!-- 消息搜索对话框 -->
    <MessageSearch
      v-model="showSearchDialog"
      @message-selected="handleMessageSelected" />
  </el-container>
</template>

<script>
import dayjs from 'dayjs'
import Search from '../components/Search.vue'
import Emoji from '../components/Emoji.vue'
import FileUpload from '../components/FileUpload.vue'
import MessageSearch from '../components/MessageSearch.vue'
import { io } from 'socket.io-client'
import http from '../utils/http'

// Element Plus 图标
import {
  Search as SearchIcon,
  Plus,
  ChatDotRound,
  VideoCamera,
  Phone,
  MoreFilled,
  Document,
  Download,
  Loading,
  Select,
  ChatLineRound,
  Paperclip,
  Picture,
  Microphone,
  Promotion
} from '@element-plus/icons-vue'
export default {
  // 注册组件
  components: {
    Search,
    Emoji,
    FileUpload,
    MessageSearch
  },
  
  data () {
    return {
      searchValue: '',
      showEmoji: false,
      showWarn: false,
      // 绑定发送消息文本框
      content: '',
      selectedIndex: 0,
      socket: null,
      showSearchDialog: false,
      // Element Plus 图标
      Search: SearchIcon,
      Plus,
      ChatDotRound,
      VideoCamera,
      Phone,
      MoreFilled,
      Document,
      Download,
      Loading,
      Select,
      ChatLineRound,
      Paperclip,
      Picture,
      Microphone,
      Promotion
    }
  },
  created () {
    // 确保用户信息已加载
    if (!this.state.user || !this.state.user.token) {
      const savedUser = localStorage.getItem('user')
      if (savedUser) {
        this.state.user = JSON.parse(savedUser)
      } else {
        // 如果没有用户信息，跳转到登录页
        this.$router.push('/login')
        return
      }
    }

    this.socket = io('ws://127.0.0.1:5000', {
      path: '/mychat',
      transports: ['websocket']
    })

    this.socket.on('connect', () => {
      console.log('Socket连接成功')
      console.log('当前用户信息:', this.state.user)

      // 发送用户登录信息
      this.socket.emit('user_login', {
        user: this.state.user,
        token: this.state.user.token
      })

      this.socket.on('disconnect', () => {
        console.log('Socket断开连接')
      })

      // 监听登录错误
      this.socket.on('login_error', (message) => {
        console.error('Socket登录错误:', message)
        alert('连接失败: ' + message)
        this.$router.push('/login')
      })

      // 监听会话列表
      this.socket.on('conversations', (conversations) => {
        console.log('收到会话列表:', conversations)
        // 可以在这里更新会话列表
      })

      // 监听未读消息数量
      this.socket.on('unread_count', (count) => {
        console.log('未读消息数量:', count)
        // 可以在这里更新未读消息提示
      })

      this.socket.on('message', (messageData) => {
        console.log('收到消息:', messageData)
        const { id, from, to, content, type, fileData, timestamp } = messageData

        // 在 recents 中找 from 好友
        let recent = this.state.recents.find(r => r.user.id === from)
        if (!recent) {
          // 如果最近聊天列表中不存在，再去好友列表中查找
          let user = null
          for(let i = 0; i < this.state.friends.length; i++) {
            const f = this.state.friends[i]
            user = f.users.find(u => u.id === from)

            if (user) break
          }

          if (user) {
            // 构建最新好友列表中的项目
            recent = {
              user: {
                id: user.id,
                nickname: user.nickname,
                icon: user.icon,
                robot: user.robot
              },
              messages: []
            }
            // 把recent添加到recents中
            this.state.recents.unshift(recent)
          }
        }

        if (recent) {
          recent.messages.push({
            id: id,
            self: false,
            content: content,
            type: type,
            fileData: fileData,
            time: timestamp ? new Date(timestamp).getTime() : Date.now()
          })

          window.localStorage.setItem('recents' + this.state.user.id, JSON.stringify(this.state.recents))

          this.$nextTick(() => {
            if (this.$refs.wrapper) {
              this.$refs.wrapper.scrollTop = this.$refs.wrapper.scrollHeight
            }
          })
        }
      })

      // 监听消息发送确认
      this.socket.on('message_sent', (data) => {
        console.log('消息发送确认:', data)
        // 可以在这里更新消息状态
      })

      // 监听消息发送错误
      this.socket.on('message_error', (error) => {
        console.error('消息发送错误:', error)
        alert('消息发送失败: ' + error)
      })
    })

  },
  computed: {
    recents () {
      return this.state.recents
    },
    currentRecent () {
      return this.state.recents[this.selectedIndex]
    },
    // 过滤后的会话列表
    filteredRecents() {
      if (!this.searchValue) {
        return this.recents
      }
      return this.recents.filter(recent =>
        recent.user.nickname.toLowerCase().includes(this.searchValue.toLowerCase()) ||
        this.lastMsgContent(recent.messages).toLowerCase().includes(this.searchValue.toLowerCase())
      )
    }
  },
  unmounted () {
    this.socket.disconnect()
  },
  watch: {
    // 监听选中的会话变化
    selectedIndex: {
      handler: async function(newIndex) {
        if (newIndex >= 0 && this.recents[newIndex]) {
          const recent = this.recents[newIndex]

          // 加载聊天历史
          if (recent && recent.user) {
            const history = await this.loadChatHistory(this.state.user.id, recent.user.id)
            if (history.length > 0) {
              // 合并历史消息和当前消息，去重
              const existingIds = new Set(recent.messages.filter(m => m.id).map(m => m.id))
              const newMessages = history.filter(msg => !existingIds.has(msg.id))

              // 将历史消息插入到开头
              recent.messages = [...newMessages, ...recent.messages]

              // 按时间排序
              recent.messages.sort((a, b) => a.time - b.time)
            }

            // 滚动到底部
            this.$nextTick(() => {
              if (this.$refs.wrapper) {
                this.$refs.wrapper.scrollTop = this.$refs.wrapper.scrollHeight
              }
            })
          }
        }
      },
      immediate: false
    },

    // 监听会话列表变化，确保有会话时自动选中第一个
    'state.recents': {
      handler: function(newRecents) {
        if (newRecents && newRecents.length > 0) {
          // 如果当前没有选中任何会话，或者选中的会话不存在，自动选中第一个
          if (this.selectedIndex >= newRecents.length || !this.currentRecent) {
            this.selectedIndex = 0
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleUpdate (code) {
      this.content += code
    },
    formatTime (time) {
      return  time ? dayjs(time).format('HH:mm') : ''
    },
    lastMsgTime (messages) {
      return this.formatTime(messages[messages.length - 1]?.time)
    },
    lastMsgContent (messages) {
      return messages[messages.length - 1]?.content
    },
    async handleSend () {
      if (!this.currentRecent) return alert('请选择要发送消息的好友')

      if (this.content.trim().length === 0) {
        this.showWarn = true
        setTimeout(() => {
          this.showWarn = false
        }, 2000)
        return
      }

      const messageContent = this.content.trim()
      const timestamp = Date.now()

      // 先添加到本地显示
      this.currentRecent?.messages.push({
        id: null, // 临时消息，没有ID
        time: timestamp,
        content: messageContent,
        type: 'text',
        self: true,
        sending: true // 标记为发送中
      })

      // 发送消息到服务器
      this.socket.emit('message', {
        from: this.state.user.id,
        to: this.currentRecent.user.id,
        content: messageContent,
        type: 'text'
      })

      // 保存到本地存储
      window.localStorage.setItem('recents' + this.state.user.id, JSON.stringify(this.state.recents))
      this.content = ''

      this.$nextTick(() => {
        if (this.$refs.wrapper) {
          this.$refs.wrapper.scrollTop = this.$refs.wrapper.scrollHeight
        }
      })
    },

    // 加载聊天历史
    async loadChatHistory(userId1, userId2) {
      try {
        const response = await this.http.get('/messages/history', {
          params: {
            userId1: userId1,
            userId2: userId2,
            limit: 50,
            offset: 0
          }
        })

        if (response.data.success) {
          return response.data.messages.map(msg => ({
            id: msg.id,
            content: msg.content,
            type: msg.type,
            self: msg.from_user_id === this.state.user.id,
            time: new Date(msg.created_at).getTime(),
            fileData: msg.file_url ? {
              url: msg.file_url,
              name: msg.file_name,
              size: msg.file_size,
              type: msg.file_type
            } : null
          }))
        }
      } catch (error) {
        console.error('加载聊天历史失败:', error)
        return []
      }
    },

    // 标记消息为已读
    async markAsRead(conversationId) {
      try {
        await this.http.post('/messages/read', {
          conversationId: conversationId
        })
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    },
    replaceEmoji (content) {
      if (content.includes('/::')) {
        this.state.emojis.forEach(e => {
          content = content.replace(e.reg, `<img src="/images/emoji/${e.file}" style="vertical-align: middle; width: 24px; height: 24px" />`)
        })
        return content
      }
      return content
    },

    // 处理单文件上传
    handleFileUploaded(file) {
      this.sendFileMessage(file)
    },

    // 处理多文件上传
    handleFilesUploaded(files) {
      files.forEach(file => {
        this.sendFileMessage(file)
      })
    },

    // 发送文件消息
    sendFileMessage(file) {
      if (!this.currentRecent) {
        alert('请选择要发送文件的好友')
        return
      }

      const timestamp = Date.now()
      const fileType = this.getFileType(file.fileType)

      // 先添加到本地显示
      this.currentRecent.messages.push({
        id: null,
        time: timestamp,
        content: file.originalName,
        type: fileType,
        self: true,
        sending: true,
        fileData: {
          url: file.url,
          name: file.originalName,
          size: file.fileSize,
          type: file.fileType
        }
      })

      // 发送文件消息到服务器
      this.socket.emit('message', {
        from: this.state.user.id,
        to: this.currentRecent.user.id,
        content: file.originalName,
        type: fileType,
        fileData: {
          url: file.url,
          name: file.originalName,
          size: file.fileSize,
          type: file.fileType
        }
      })

      // 保存到本地存储
      window.localStorage.setItem('recents' + this.state.user.id, JSON.stringify(this.state.recents))

      this.$nextTick(() => {
        if (this.$refs.wrapper) {
          this.$refs.wrapper.scrollTop = this.$refs.wrapper.scrollHeight
        }
      })
    },

    // 获取文件类型
    getFileType(mimeType) {
      if (mimeType.startsWith('image/')) return 'image'
      if (mimeType.startsWith('video/')) return 'video'
      if (mimeType.startsWith('audio/')) return 'audio'
      return 'file'
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 处理搜索消息选择
    handleMessageSelected(message) {
      console.log('选中搜索消息:', message)
      // 可以在这里实现跳转到对应的聊天记录
      // 比如找到对应的用户并切换到该会话

      // 简单实现：显示消息详情
      alert(`消息详情:\n发送者: ${message.sender_nickname}\n内容: ${message.content}\n时间: ${this.formatTime(new Date(message.created_at).getTime())}`)
    },

    // 获取未读消息数量
    getUnreadCount(recent) {
      // 这里可以实现真实的未读消息计算逻辑
      // 暂时返回0，后续可以根据实际需求实现
      return 0
    },

    // 判断是否显示时间分隔线
    shouldShowTime(index) {
      if (index === 0) return true

      const currentMsg = this.currentRecent.messages[index]
      const prevMsg = this.currentRecent.messages[index - 1]

      // 如果两条消息间隔超过5分钟，显示时间
      const timeDiff = currentMsg.time - prevMsg.time
      return timeDiff > 5 * 60 * 1000
    },

    // 预览图片
    previewImage(url) {
      // 简单实现：在新窗口打开图片
      window.open(url, '_blank')
    },

    // 下载文件
    downloadFile(url) {
      const link = document.createElement('a')
      link.href = this.getImageUrl(url)
      link.download = ''
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 转换图片URL路径
    getImageUrl(url) {
      if (!url) return ''

      // 如果已经是完整的URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }

      // 如果是 /api/files/ 开头的路径，转换为实际的文件路径
      if (url.startsWith('/api/files/')) {
        const filename = url.replace('/api/files/', '')
        // 根据文件扩展名判断文件类型
        const ext = filename.split('.').pop().toLowerCase()

        if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(ext)) {
          return `http://localhost:5000/uploads/images/${filename}`
        } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'].includes(ext)) {
          return `http://localhost:5000/uploads/videos/${filename}`
        } else if (['mp3', 'wav', 'ogg', 'aac', 'm4a'].includes(ext)) {
          return `http://localhost:5000/uploads/audios/${filename}`
        } else {
          return `http://localhost:5000/uploads/files/${filename}`
        }
      }

      // 其他情况直接返回原URL
      return url
    }
  }
}
</script>

<style scoped>
/* 主布局 */
.chat-layout {
  height: 100vh;
  background: #f5f7fa;
}

/* 左侧边栏 */
.chat-sidebar {
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  border-right: 1px solid var(--el-border-color-light);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.sidebar-header {
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 0 20px;
  background: white;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.header-content h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.search-container {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: white;
}

.search-container .el-input {
  border-radius: 20px;
}

/* 会话列表 */
.conversation-scrollbar {
  height: calc(100vh - 120px);
}

.conversation-list {
  padding: 12px 8px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 16px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  border-radius: 12px;
  margin-bottom: 4px;
}

.conversation-item:hover {
  background: rgba(102, 126, 234, 0.08);
  transform: translateX(4px);
}

.conversation-item.active {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%);
  border-left: 4px solid var(--el-color-primary);
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.2);
}

.conversation-badge {
  margin-right: 16px;
  position: relative;
}

.conversation-avatar {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.conversation-item:hover .conversation-avatar {
  transform: scale(1.05);
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
  gap: 8px;
}

.name {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-size: 15px;
  flex: 1;
}

.time {
  font-size: 11px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  background: rgba(0, 0, 0, 0.05);
  padding: 2px 6px;
  border-radius: 8px;
}

.last-message {
  display: flex;
  align-items: center;
}

.content {
  font-size: 13px;
  color: var(--el-text-color-regular);
  opacity: 0.8;
}

/* 聊天主区域 */
.chat-main {
  background: white;
  display: flex;
  flex-direction: column;
}

/* 聊天内容包装器 */
.chat-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去头部高度 */
}

.chat-header {
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 0 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.chat-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.chat-info .el-avatar {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  border: 2px solid white;
}

.header-text h4 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-text .el-text {
  font-size: 12px;
  font-weight: 500;
}

.chat-actions .el-button-group .el-button {
  border-radius: 8px;
  margin-left: 4px;
  transition: all 0.2s ease;
}

.chat-actions .el-button-group .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 消息容器 */
.messages-container {
  flex: 1;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  overflow: hidden;
}

.messages-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="%23ffffff" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="%23ffffff" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="%23ffffff" opacity="0.05"/><circle cx="20" cy="80" r="0.5" fill="%23ffffff" opacity="0.05"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
  pointer-events: none;
}

.messages-scrollbar {
  height: 100%;
  padding: 20px;
  position: relative;
  z-index: 1;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 时间分隔线 */
.time-divider {
  margin: 16px 0;
  text-align: center;
}

.time-divider :deep(.el-divider__text) {
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  color: #666;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

/* 消息项 */
.message-item {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  max-width: 75%;
  animation: messageSlideIn 0.3s ease-out;
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-item.message-self {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  position: relative;
}

.message-avatar img {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: transform 0.2s ease;
}

.message-avatar img:hover {
  transform: scale(1.05);
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}

.message-self .message-content {
  align-items: flex-end;
}

/* 消息气泡 */
.message-bubble {
  max-width: 100%;
  word-wrap: break-word;
  position: relative;
  border-radius: 18px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.message-bubble:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 文本消息 */
.text-message {
  background: white;
  border: none;
  padding: 12px 16px;
  line-height: 1.5;
  position: relative;
}

.text-message::before {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 20px;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid white;
}

.message-self .text-message {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-self .text-message::before {
  left: auto;
  right: 20px;
  border-top-color: #667eea;
}

/* 图片消息 */
.image-message {
  background: white;
  border: none;
  padding: 8px;
  border-radius: 12px;
  overflow: hidden;
  max-width: 280px;
}

.chat-image {
  width: 100%;
  max-width: 260px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.chat-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.image-placeholder,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
  gap: 8px;
}

.image-placeholder .el-icon,
.image-error .el-icon {
  font-size: 24px;
}

.image-info {
  margin-top: 6px;
  padding: 0 4px;
  text-align: center;
}

/* 视频消息 */
.video-message {
  background: white;
  border: none;
  padding: 8px;
  border-radius: 12px;
  overflow: hidden;
  max-width: 320px;
}

.chat-video {
  width: 100%;
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  outline: none;
}

.video-info {
  margin-top: 6px;
  padding: 0 4px;
  text-align: center;
}

/* 音频消息 */
.audio-message {
  background: white;
  border: none;
  padding: 12px;
  border-radius: 12px;
  min-width: 200px;
  max-width: 280px;
}

.audio-player {
  display: flex;
  align-items: center;
  gap: 12px;
}

.audio-icon {
  font-size: 24px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-color-primary-light-9);
  border-radius: 50%;
}

.chat-audio {
  flex: 1;
  height: 32px;
  outline: none;
}

.audio-info {
  margin-top: 8px;
  text-align: center;
}

/* 文件消息 */
.file-message {
  background: white;
  border: none;
  padding: 16px;
  min-width: 240px;
}

.file-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.file-details .el-text {
  color: #666;
}

/* 消息状态 */
.message-status {
  margin-top: 6px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.8);
}

/* 输入区域 */
.input-area {
  flex-shrink: 0;
  border-top: 1px solid var(--el-border-color-lighter);
  background: white;
  padding: 16px 20px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  min-height: 120px;
}

/* 输入工具栏 */
.input-toolbar {
  padding: 8px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.input-toolbar-buttons {
  display: flex;
  align-items: center;
  gap: 4px;
}

.input-toolbar-buttons .el-button {
  margin: 0;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: #f8f9fa;
  border-radius: 24px;
  padding: 8px;
  border: 2px solid transparent;
  transition: all 0.2s ease;
}

.input-container:focus-within {
  border-color: var(--el-color-primary);
  background: white;
  box-shadow: 0 0 0 4px var(--el-color-primary-light-9);
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
  resize: none;
  outline: none;
  font-size: 14px;
  line-height: 1.5;
  padding: 8px 12px;
  border-radius: 16px;
  transition: all 0.2s ease;
}

.message-input:focus {
  background: transparent;
}

.send-button {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.send-button:hover:not(:disabled) {
  transform: scale(1.1) rotate(5deg);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
}

.send-button:disabled {
  background: #e9ecef;
  color: #adb5bd;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.input-warning {
  margin-top: 12px;
  border-radius: 8px;
  border: none;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-sidebar {
    position: absolute;
    z-index: 1000;
    height: 100%;
    width: 100% !important;
  }

  .message-item {
    max-width: 85%;
  }
}
</style>